package com.mlk.core.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mlk.core.component.ProjectInfoBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 项目信息配置
 * 该web lisener会加载project-info.json文件内容
 */
@WebListener
@Slf4j
class ProjectInfoConfig implements ServletContextListener {
    /**
     * 加载的项目的基础信息的配置文件名称
     */
    private static final String PROJECT_INFO_PATH = "project-info.json";
    /**
     * 存储在application域之中的项目信息的key
     */
    public static final String PROJECT_INFO_KEY = "project";

    @Override
    public void contextInitialized(ServletContextEvent context) {
        log.info("ProjectInfoConfig init");
        ClassPathResource resource = new ClassPathResource(PROJECT_INFO_PATH);
        String json = null;
        try {
            json = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()), Charset.forName("utf-8"));
        } catch (IOException e) {
            log.error("project-info.json不存在");
        }
        ObjectMapper mapper = new ObjectMapper();
        ProjectInfoBean bean = null;
        try {
            bean = mapper.readValue(json, ProjectInfoBean.class);
        } catch (IOException e) {
            log.error("json 解析出现问题", e);
        }

        // 向application之中存储项目的基础信息
        context.getServletContext().setAttribute(PROJECT_INFO_KEY, bean);
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        log.info("ProjectInfoConfig destroyed");
    }


}


